// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Spin, Form, Select, Input, DatePicker, Button, Row, Col, Icon, Modal, Tabs, message } from 'antd'
import moment from 'moment';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './activityAreaStyle.less'
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'
//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'
const confirm = Modal.confirm;
const { TabPane } = Tabs;
const Option = Select.Option;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */

const infoListAdminView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model

  // modelObj.xxx获取model中状态机的值
  let { showModal, imgLoading,
    zmzjCode } = modelObj
  // 资讯新增/编辑/详情页跳转
  function addOrEditSkip(type, id) {
    hashHistory.push({
      pathname: '/home/infoAdmin/activityAreaDetail',
      query: { actionType: type, activityAreaId: id }
    })
  }
  function deleteContent(id) {
    confirm({
      title: '删除确认',
      content: '您真的要删除此条活动专区吗?',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        console.group(id)
        dispatch({
          type: `${namespace}/deleteActivityArea`,
          payload: { activityAreaId: id }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  // 跳转统计页面
  function statistics(id) {
    hashHistory.push({
      pathname: '/home/infoAdmin/activityAreaStatistics',
      query: { id }
    });
  }
  // 复制小程序链接
  function copyLink(item) {
    let input = document.querySelector('#copy_ele')
    if (!input) {
      input = document.createElement('input');
      input.id = 'copy_ele';
      document.getElementById('gug').appendChild(input);
    }
    input.value = ` /subPackages3/pages/activityArea/activityAreaList/activityAreaList?activityAreaId=${item.activityAreaId}`;
    input.style.opacity = 0;
    try {
      input.select(); // 选择对象
      document.execCommand("Copy");
      message.success('复制成功，链接复制到剪切板中！')
    } catch (error) {
      message.error('复制失败，请刷新页面重试！')
    }

  }
  // 获取小程序码并展示
  function previewSkip(item) {
    let { id, counselorAccountId, activityAreaId } = item;
    let page = `subPackages3/pages/activityArea/activityAreaList/activityAreaList`;
    // let page = `subPackages2/pages/liveRoom/wxcodeTransferStation/wxcodeTransferStation`;
    // if (uuseeAppId != config.zmzjAppKey) {
    //   params = {
    //     projectId: projectId,
    //     productId: productId
    //   }
    //   page = `subPackages3/pages/liveManage/liveList/liveList`;
    // }
    dispatch({
      type: `${namespace}/generateQrCode`,
      payload: {
        channelType: 0,
        activityAreaId,
        params: {
          page
        },
        page: page,
      }
    })
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { showModal: true }
    });
  }
  function hideModal() {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { showModal: false }
    });
  }
  let pageProps = {
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: `admin/activityArea/list`,
      // 接口方式
      method: "POST",
      // "data_field_name":"data",
      app: "",
      // 接口参数
      params: {
      },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,
      // 查询栏
      search_bar: {
        fields: [
          {
            en_name: 'activityAreaName',
            zh_name: '专区名称',
            elem_type: 'Input',
            elem_valid_type: 'string',
            //关联的更改的搜索字段
            // related_key: 'businessId',
            // //请求地址
            // related_req_url: 'admin/estate/list',
            // //默认请求
            // related_req_param: {
            //   pageNo: 1,
            //   pageSize: 1000
            // }
          },

          {
            en_name: 'status',
            zh_name: '状态',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: [
              {
                value: '0',
                label: '未发布'
              },
              {
                value: '1',
                label: '已发布'
              },
            ],
          }
        ],
        searchHandler: () => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click')
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'channel',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格  序号  活动标题  活动日期 所属项目 所属城市 报名人数 创建人 创建时间 更新人 更新时间
      table:
      {
        status_params: "status=0",
        status_text: "全部",
        // 表头字段列表
        scroll: { x: 1000 },
        fields: [
          {
            en_name: "activityAreaName",
            zh_name: "专区名称",
            //width:130
          },

          {
            en_name: "regionName",
            zh_name: "所属区域",
            // width:180
          },
          {
            en_name: "status",
            zh_name: "发布状态",
            render: (a, item, index, d, e, f) => {
              return a == 0 ? '未发布' : '已发布'
            }
            // width:180
          },
          {
            en_name: "creator",
            zh_name: "更新人",
            // width:80,
          },
          {
            en_name: "createTime",
            zh_name: "更新时间",
            // width:180
          },
          {
            en_name: "edit",
            zh_name: "操作",
            // width:160,
            // fixed:'right',
            render: (a, item, index, d, e, f) => {
              return (
                <span>
                  <FlagBtn node={<a onClick={() => copyLink(item)}>复制链接<span className="ant-divider" /></a>} btnId={''}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => previewSkip(item)}>小程序码<span className="ant-divider" /></a>} btnId={'20202'}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => statistics(item.activityAreaId)}>统计<span className="ant-divider" /></a>} btnId={'20203'}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => addOrEditSkip('edit', item.activityAreaId)}>编辑<span className="ant-divider" /></a>} btnId={'20203'}> </FlagBtn>
                  {item.status == 0 ? <FlagBtn node={<a onClick={() => deleteContent(item.activityAreaId)}>删除</a>} btnId={'20104'}> </FlagBtn> : null}
                  {/* <a onClick={() => deleteContent(item.contentId)}>删除</a> */}
                </span>
              )
            },
          }
        ]
      },
      // 操作栏
      action_bar: [
        {
          func_name: "add",
          label: "新建专区",
          btnId: '20201',
          type: "primary",
          onClick: (e) => {
            hashHistory.push({
              pathname: MODULE_TO_ROUTES[namespace].urlArray[0],
              query: { actionType: 'add' }
            });

          }
        }
      ]
    },
  }
  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz }
      })
    }
  }

  return (
    <div id="gug" className={cx('pageLayout')}>
      <ListPage pageProps={pageProps} />
      <Modal
        maskClosable={true}
        onCancel={() => { hideModal() }}
        visible={showModal}
        footer={null}>
        <Tabs defaultActiveKey="2" size={'small'}>
          <TabPane tab="美的置业云" key="2">
            {
              imgLoading ?
                <div className={styles.codeClass}>
                  <Spin tip='Loading...' size='large'></Spin>
                </div> :
                <img className={styles.codeClass} src={zmzjCode} />
            }

          </TabPane>
          {/* <TabPane tab="置业神器" key="1">
            {
              imgLoading?
                  <div className={styles.codeClass}>
                    <Spin tip='Loading...' size='large'></Spin>
                  </div> :
                  <img className={styles.codeClass} src={zysqCode}/>
            }
          </TabPane> */}
        </Tabs>
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(infoListAdminView))